<?php

namespace app\model;

use think\facade\Cache;
use think\Model;
use think\model\relation\HasMany;

class AdminAccount extends Model
{
    public function addOrUpdate(): array
    {
        $param = request()->post();
        $count = $this->when(!empty($param['id']), function ($query) use ($param) {
            $query->where('id', '<>', $param['id']);
        })->where('account', $param['account'])->count();
        if ($count > 0) throw new \Exception('账号已存在');
        if (!empty($param['password'])) {
            $pwd = setPassword($param['password']);
            $param['password'] = $pwd['password'];
            $param['token'] = $pwd['token'];
        } else unset($param['password']);
        $merchant = $param['merchant_lst'];
        unset($param['merchant_lst']);
        $this->startTrans();
        $this->exists(!empty($param['id']))->save($param);
        $model = app(AdminMerchant::class);
        $model->where('aid', $this->id)->delete();
        if (!empty($merchant)) {
            $id = $this->id;
            $model->saveAll(array_map(function ($its) use ($id) {
                return ['aid' => $id, 'mer_id' => $its];
            }, $merchant));
        }
        $this->commit();
        return $this->toArray();
    }

    public function login(): array
    {
        $param = request()->param();
        $user = $this->where("account", $param['username'])->find();
        if (empty($user)) throw new \Exception("用户不存在", 70354);
        if (!checkPassword($param['password'], $user['token'], $user['password'])) throw new \Exception("密码错误", 70354);
        $token = setCacheToken();
        Cache::set("admin_" . $token, [
            "id" => $user['id'],
            "account" => $user['account'],
            "token" => $token
        ], 24 * 60 * 60);
        return [
            "token" => $token,
            "aid" => $user['id']
        ];
    }

    public function merchant(): HasMany
    {
        return $this->hasMany(AdminMerchant::class, "aid");
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->with(['merchant' => function ($query) {
            $query->with(['merchant']);
        }])->order('create_time', 'desc')->paginate([
            'list_rows' => $param['size'] ?? 30,
            'page' => $param['page'] ?? 1
        ])->toArray();
        if (!empty($data['data'])) {
            $mod = app(SysRole::class);
            foreach ($data['data'] as &$item) {
                $item['role_its'] = [];
                if (!empty($item['role'])) {
                    $item['role_its'] = $mod->whereIn('id', $item['role'])->column('name');
                }
            }
        }
        return pageData($data);
    }

    public function detail()
    {
        $param = request()->param();
        $data = $this->with(['merchant'])->find($param['id'])->hidden(['password']);
        if (!empty($data)) {
            $data = $data->toArray();
            $data['merchant_lst'] = array_column($data['merchant'], "mer_id");
            unset($data['merchant']);
        }
        return $data;
    }
}
